package de.tabreaderandroid.tabreader.preferences;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

/**
 * Manages the editing of available folder using SQLite.
 * 
 * @author André Stannek
 * 
 */
public class FolderRepository {

	private SQLHelper sqlHelper;

	/**
	 * @param context
	 *            the {@link Context} this repository is used in
	 */
	public FolderRepository(final Context context) {
		super();
		sqlHelper = new SQLHelper(context);
	}

	/**
	 * Adds a new folder to available folders.
	 * 
	 * @param path
	 *            the path of the folder
	 */
	public void addFolder(final String path) {
		ContentValues values = new ContentValues();
		values.put(SQLHelper.COLUMN_FOLDER, path);
		sqlHelper.getWritableDatabase().insert(SQLHelper.TABLE_FOLDERS, null,
				values);
		sqlHelper.close();
	}

	/**
	 * Deletes an existing folder from available folders.
	 * 
	 * @param folder
	 *            the path of the folder
	 */
	public void deleteFolder(final String folder) {
		sqlHelper.getWritableDatabase().delete(SQLHelper.TABLE_FOLDERS,
				SQLHelper.COLUMN_FOLDER + " = \"" + folder + "\"", null);
		sqlHelper.close();
	}

	/**
	 * @return all available folders
	 */
	public List<String> getAllFolders() {
		List<String> folders = new ArrayList<String>();

		Cursor cursor = sqlHelper.getWritableDatabase().query(
				SQLHelper.TABLE_FOLDERS, null, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {

			folders.add(cursor.getString(0));
			cursor.moveToNext();
		}
		cursor.close();
		sqlHelper.close();
		return folders;
	}
}
